package duyd.hibernate.training.test;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import duyd.hibernate.training.domain.Event;

public class HibernateJPA {

	protected EntityManagerFactory entityManagerFactory;

	@Before
	public void setUp() throws Exception {
		// like discussed with regards to SessionFactory, an
		// EntityManagerFactory is set up once for an application
		// IMPORTANT: notice how the name here matches the name we gave the
		// persistence-unit in persistence.xml!
		entityManagerFactory = Persistence
				.createEntityManagerFactory("duyd.hibernate.training");
	}

	@After
	public void tearDown() throws Exception {
		if (entityManagerFactory != null) {
			entityManagerFactory.close();
		}
	}

	@Test
	public void test() {
		// create a couple of events...
		// Session session = sessionFactory.openSession();
		// session.beginTransaction();
		// session.save(new Event("Our very first event!", new Date()));
		// session.save(new Event("A follow up event", new Date()));
		// session.getTransaction().commit();
		// session.close();
		//
		// // now lets pull events from the database and list them
		// session = sessionFactory.openSession();
		// session.beginTransaction();
		// List<Event> result = session.createQuery("from Event").list();
		// for (Event event : (List<Event>) result) {
		// System.out.println("Event (" + event.getDate() + ") : "
		// + event.getTitle());
		// }
		// session.getTransaction().commit();
		// session.close();

		// create a couple of events...
		EntityManager entityManager = entityManagerFactory
				.createEntityManager();
		entityManager.getTransaction().begin();
		entityManager.persist(new Event("Our very first event!", new Date()));
		entityManager.persist(new Event("A follow up event", new Date()));
		entityManager.getTransaction().commit();
		entityManager.close();

		// now lets pull events from the database and list them
		entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
		List<Event> result = entityManager.createQuery("from Event",
				Event.class).getResultList();
		for (Event event : result) {
			System.out.println("Event (" + event.getDate() + ") : "
					+ event.getTitle());
		}
		entityManager.getTransaction().commit();
		entityManager.close();
	}

}
